import { defineStore } from 'pinia'

export const useOrderStore = defineStore('orderStore', {
  state: () => ({
    orders: [],
    initialized: false
  }),

  getters: {
    getOrderById: (state) => (id) => state.orders.find(o => o.id === id)
  },

  actions: {
    initialize() {
      if (!this.initialized) {
        const storedOrders = localStorage.getItem('purchaseOrders')
        this.orders = storedOrders ? JSON.parse(storedOrders) : []
        this.initialized = true
      }
    },

    setOrders(orders) {
      this.orders = orders
      this.persist()
    },

    addOrder(order) {
      // 检查是否已存在相同ID的订单
      const index = this.orders.findIndex(o => o.id === order.id)
      if (index !== -1) {
        // 更新现有订单
        this.orders[index] = order
      } else {
        // 添加新订单到最前面
        this.orders.unshift(order)
      }
      this.persist()
    },

    updateOrder(updated) {
      const index = this.orders.findIndex(o => o.id === updated.id)
      if (index !== -1) {
        this.orders[index] = { ...updated }
        this.persist()
      }
    },

    deleteOrder(id) {
      this.orders = this.orders.filter(o => o.id !== id)
      this.persist()
    },

    persist() {
      localStorage.setItem('purchaseOrders', JSON.stringify(this.orders))
    }
  }
}) 